﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

using System.Diagnostics;
using System.Diagnostics.Eventing;



namespace ProtocolsFeature.EventReceivers.IncomingDocumentHandlers
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class IncomingDocumentHandlers : SPItemEventReceiver
    {

     

       public override void ItemUpdated(SPItemEventProperties properties)
       {
           base.ItemUpdated(properties);


           SPListItem item = properties.ListItem;


           if (item[item.ParentList.Fields.GetFieldByInternalName("ProtocolID").Id] == null)
           {

               string protocolID = BuildProtocolID(item);

               if (!string.IsNullOrEmpty(protocolID))
               {
                   SPSecurity.RunWithElevatedPrivileges(delegate()
                   {
                       this.EventFiringEnabled = false;
                       try
                       {
                           using (SPSite site = new SPSite(item.Web.Url))
                           {
                               site.AllowUnsafeUpdates = true;

                               using (SPWeb web = site.OpenWeb())
                               {

                                   web.AllowUnsafeUpdates = true;

                                   SPListItem itemToUpdate = web.Lists[item.ParentList.ID].GetItemById(item.ID);

                                  
                                   itemToUpdate[itemToUpdate.ParentList.Fields.GetFieldByInternalName("ProtocolID").Id] = protocolID;
                                   itemToUpdate[itemToUpdate.ParentList.Fields.GetFieldByInternalName("ProtocolDate").Id] = DateTime.Now;

                                   itemToUpdate.UpdateOverwriteVersion();
                                   

                               }

                           }
                       }
                       catch (Exception codeException)
                       {
                           WriteError(codeException);
                       }

                       this.EventFiringEnabled = true;

                   });


               }

           }



       }


       private string BuildProtocolID(SPListItem item)
       {
           string protocolID = "";


           // Get the forumula for the list.

           SPList configList = item.Web.GetList(string.Format("{0}/Lists/{1}", item.Web.ServerRelativeUrl, "LibraryConfiguration"));

           foreach (SPListItem configItem in configList.Items)
           {

               if (configItem["ListName"].ToString() == item.ParentList.Title)
               {


                   if (configItem[configItem.ParentList.Fields.GetFieldByInternalName("Formula").Id] != null)
                   {

                       string formula = configItem[configItem.ParentList.Fields.GetFieldByInternalName("Formula").Id].ToString();

                       protocolID = formula;

                       int startPos = 0;
                       int endPos = 0;
                       string formulaString = "";


                    

                       #region Replace "AUTOID" token - use the ID to avoid duplicate ids
                       try
                       {
                           if (protocolID.Contains("AUTOID"))
                           {


                               int id = 0;

                               try
                               {

                                   // Get any offset so we can start the number schema from any position
                                   id = int.Parse(configItem[configItem.ParentList.Fields.GetFieldByInternalName("IDOffset").Id].ToString());
                               }
                               catch (Exception codeException)
                               {
                                   WriteError(codeException);
                               }



                               startPos = protocolID.IndexOf("AUTOID[");
                               endPos = protocolID.IndexOf("]", startPos + 1);

                               formulaString = protocolID.Substring(startPos, endPos - startPos + 1);

                               string padLen = formulaString.Replace("AUTOID[", "").Replace("]", "");

                               // Insert the replacement string

                               id = id + item.ID;

                               protocolID = protocolID.Replace(formulaString, id.ToString().PadLeft(int.Parse(padLen), '0'));
                           }
                       }
                       catch (Exception codeException)
                       {
                           WriteError(codeException);
                       }



                       #endregion

                       #region Replace "DATE" token
                       try
                       {
                           if (protocolID.Contains("DATE"))
                           {

                               startPos = protocolID.IndexOf("DATE[");
                               endPos = protocolID.IndexOf("]", startPos + 1);

                               formulaString = protocolID.Substring(startPos, endPos - startPos + 1);

                               string dateFormatString = formulaString.Replace("DATE[", "").Replace("]", "");


                               // Insert the replacement string
                               protocolID = protocolID.Replace(formulaString, DateTime.Today.ToString(dateFormatString));

                           }
                       }
                       catch (Exception codeException)
                       {
                           WriteError(codeException);
                       }


                       #endregion

                   }

                   break;
               }


           }


           return protocolID;
       }

 
       #region Code for creating sub-folders by category
       private string GetValueFromLookup(string itemContent)
       {

           string value = "";

           if (!string.IsNullOrEmpty(itemContent))
           {
               value = itemContent.Substring(itemContent.IndexOf("#;") + 2);
           }

           return value;
       }



       private void WriteError(Exception ex)
       {

           EventLog LogToSystem = new EventLog();

           LogToSystem.Source = "SharePoint 2010 Protocols Library";
           LogToSystem.WriteEntry(ex.Message + " : " + ex.StackTrace, EventLogEntryType.Error);

       }

   
       #endregion



    }
}
